package operate.node;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;

import java.util.List;

/**
 * @author m0v1
 * @date 2021年09月07日 8:06 上午
 */
public class WatchNode extends AbstractNodeOperation {
    @Override
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            try {
                System.out.println("path:" + watchedEvent.getPath());
                // 如果watch为true,当更新该节点数据或删除该节点或更新子节点列表都会重新触发当前事件
                byte[] data = zooKeeper.getData("/zk-permanent-node", true, null);
                System.out.println("data of node:/zk-permanent-node is " + new String(data));
                System.out.println(getChildrenNodes());
                System.out.println("======================================");
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 监听子节点列表改变事件
        // 注:已有子节点数据的更新不会触发改事件
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            System.out.println("path:" + watchedEvent.getPath());
            try {
                System.out.println("children nodes changed...");
                List<String> children = getChildrenNodes();
                System.out.println("children nodes are " + children);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

    private List<String> getChildrenNodes() throws KeeperException, InterruptedException {
        return zooKeeper.getChildren("/zk-permanent-node", true);
    }
}
